<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编号" prop="qrcodeId">
        <el-input
          v-model="queryParams.qrcodeId"
          placeholder="请输入编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="积分" prop="score">
        <el-input
          v-model="queryParams.score"
          placeholder="请输入积分"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="score">
      <el-select v-model="queryParams.status" placeholder="请选择">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      </el-form-item>
      <el-form-item label="是否打印" prop="score">
        <el-select v-model="queryParams.print" placeholder="请选择">
          <el-option
            v-for="item in optionsPrint"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:qrcode:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:qrcode:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:qrcode:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:qrcode:export']"
        >导出</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-printer"-->
<!--          size="mini"-->
<!--          @click="handlePrint"-->
<!--          v-hasPermi="['system:qrcode:export']"-->
<!--        >打印</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="qrcodeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="二维码id" align="center" prop="qrcodeId" />
      <el-table-column label="图片" align="center" prop="imagePath" >
          <template slot-scope="scope">
            <el-image
              lazy
              style="width: 100px; height: 100px"
              :preview-src-list="scope.row.imagePath|getAvatarList"
              :src="scope.row.imagePath|getAvatar">
            </el-image>
          </template>
      </el-table-column>
      <el-table-column label="积分" align="center" prop="score" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status|statusType">{{scope.row.status|statusText}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否打印" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.print?'danger':'success'">{{scope.row.print?'已打印':'未打印'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:qrcode:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:qrcode:remove']"
          >删除</el-button>

          <el-button
          size="mini"
          type="text"
          icon="el-icon-printer"
          @click="handleExport(scope.row)"
          v-hasPermi="['system:qrcode:export']"
        >导出</el-button>
        </template>


      </el-table-column>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改二维码对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="生成数量" prop="num" v-if="isAdd">
          <el-input-number v-model="form.num" :min="1" :max="50" label="生成数量"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status" v-if="!isAdd">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="积分" prop="score">
          <el-input v-model="form.score" placeholder="请输入积分" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQrcode, getQrcode, delQrcode, addQrcode, updateQrcode } from "@/api/system/qrcode"
import { Loading } from 'element-ui';
import {
  STATUS,
  getStatus,
  getAvatar,
  getAvatarList,
  STATUS_OPTIONS,
  STATUS_PRINT_OPTIONS
} from "../../../utils/jpUtils";
export default {
  name: "Qrcode",
  data() {
    return {
      isAdd:false,
      // //0正常 1停用 2已经使用）
      options: STATUS_OPTIONS(),
      optionsPrint:STATUS_PRINT_OPTIONS(),
      screenInstance:'',
      addLoading:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 二维码表格数据
      qrcodeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        print:null,
        pageNum: 1,
        pageSize: 10,
        qrcodeId: null,
        score: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getList()
  },
  filters: {
    statusText(val){
      //0正常 1停用 2已经使用）
      return getStatus(val).txt
    },
    statusType(val){
      return getStatus(val).type
    },
    getAvatarList,
    getAvatar
  },
  methods: {
    /** 查询二维码列表 */
    getList() {
      this.loading = true
      listQrcode(this.queryParams).then(response => {
        this.qrcodeList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        print:null,
        qrcodeId: null,
        num:1,
        imagePath: null,
        score: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams.print=null
      this.queryParams.status=null
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.qrcodeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.isAdd = true;
      this.title = "添加二维码"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isAdd = false;
      this.reset()
      const qrcodeId = row.qrcodeId || this.ids
      getQrcode(qrcodeId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改二维码"
      })
    },
    showScreen(txt){
      console.log('scree')
      this.screenInstance = Loading.service({ lock: true,
        text: txt||'loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)' });
    },
    closeScreen(){
      this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
        this.screenInstance.close();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.qrcodeId != null) {
            this.showScreen()
            //this.isAdd = false
            updateQrcode(this.form).then(response => {
              this.closeScreen()
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            }).catch(e=>{
              this.closeScreen()
            })
          } else {
           // console.log('sss')
            this.showScreen("添加中")
            //this.isAdd = true
            addQrcode(this.form).then(response => {
              this.closeScreen()
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            }).catch(e=>{
              this.closeScreen()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const qrcodeIds = row.qrcodeId || this.ids
      this.$modal.confirm('是否确认删除二维码编号为"' + qrcodeIds + '"的数据项？').then(function() {
        return delQrcode(qrcodeIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    handlePrint(){
      //hiPrintPlugin.disAutoConnect();
    //  this.$printPlugin.print();
      // 组件
   //   hiprint.init();
      // 初始化
  //    const hiprintTemplate = new hiprint.PrintTemplate()

// 因为我个人觉的直接通过打印某个元素区域最好用(最好上手)所以使用的是打印html的方式
  //    hiprintTemplate.printByHtml("<h1>ccdsw</h1>",{});
     // window.print();
    },
    /** 导出按钮操作 */
    handleExport(data) {
      this.$alert('如果导出已经打印过的二维码，二维码会有黄颜色边框用于区分，不影响打印效果', '系统提示', {
        confirmButtonText: '知道了,继续导出',
        callback: action => {
          let printId=''
          if(data){
            printId = data.qrcodeId
          }
          let ids=[]
          if(this.ids)
            ids = this.ids

          let _this = this
          this.download('system/qrcode/export', {
            ...this.queryParams,printId,ids
          }, `qrcode_${new Date().getTime()}.pdf`,{},()=>{
            _this.getList()
          })
        }
      });


    //   const down = () => {
    //     const url = 'http://127.0.0.1:8080/system/qrcode/export'
    //     //const filename = '操作指南'
    //     const x = new XMLHttpRequest()
    //     x.open('POST', url, true)
    //     x.responseType = 'blob'
    //     x.onload = e => {
    //       // 会创建一个 DOMString，其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
    //       const url = window.URL.createObjectURL(x.response)
    //       const a = document.createElement('a')
    //       a.href = url
    //     //  a.download = filename
    //       a.click()
    //     }
    //     x.send()
    //   }
    //  down()
     }
  }
}
</script>
